package com.jxb.test20241021;

public class LeakyBucket1 {

    private static long rate = 5L;//每秒钟，处理5个请求

    private static long size = 10L;//桶容量

    private static long capacity;

    private static boolean isLimit;


    public static void main(String[] args) {
        //后台限流监测
        new Thread(new Runnable() {
            @Override
            public void run() {
                limit();
            }
        }).start();

        //模拟高并发
        while (true) {
            try {
                Thread.sleep(19);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (isLimit) {
                System.out.println("限流了... ...");
            }else {
                capacity++;
            }
        }
    }

    public static void limit() {
        while (true) {
            if (capacity >= size) {
                //限流
                isLimit = true;
            }else {
                //模拟后台系统执行
                capacity = capacity - rate;
                isLimit = false;
            }
            //模拟每秒执行一次
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}
